<template>

  <el-dialog :title="id ? '通道修改' : '通道添加'" :visible.sync="dialogVisible" width="60%" :close-on-click-modal="false">

    <el-form ref="main-form" :model="form" :rules="rules" label-width="160px" :inline="true">
      <el-form-item label="通道编号" size="mini" prop="channelNo" v-if="id">
        <el-input placeholder="" v-model="form.channelNo" @keyup.enter.native="submit" :disabled="id ? true : false" clearable></el-input>
      </el-form-item>

      <el-form-item label="通道名称" size="mini" prop="channelName">
        <el-input placeholder="" v-model="form.channelName" @keyup.enter.native="submit" clearable></el-input>
      </el-form-item>

      <el-form-item label="所属银行" size="mini" prop="bankId">
        <el-select v-model="form.bankId" size="small" clearable :disabled="id ? true : false" @change="bankChange">
          <el-option v-for="item in bankOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="结算币种（单选）" size="mini" prop="settleCurrency">
        <el-select v-model="form.settleCurrency" size="small" clearable>
          <el-option v-for="item in currencyOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="卡种" size="mini" prop="cardType">
        <el-select v-model="form.cardType" size="small" clearable>
          <el-option
            v-for="item in cardTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="支付类型" size="mini" prop="payType">
        <el-select v-model="form.payType" size="small" clearable>
          <el-option v-for="item in payTypeOption" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="国家" size="mini" prop="country">
        <el-input placeholder="" v-model="form.country" @keyup.enter.native="submit" clearable></el-input>
      </el-form-item>

      <el-form-item label="风控集合" size="mini" prop="riskCollectionId">
        <el-select v-model="form.riskCollectionId" size="small" clearable>
          <el-option v-for="item in riskCollectionOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="备注" size="mini" prop="remark">
        <el-input placeholder="" v-model="form.remark" @keyup.enter.native="submit" clearable></el-input>
      </el-form-item>

      <el-form-item label="状态" size="mini" prop="status">
        <el-switch active-value="1" inactive-value="0" v-model="form.status" active-color="#13ce66" inactive-color="#ff4949">
        </el-switch>
      </el-form-item>

      <el-row>
        <el-form-item label="可支付" size="mini" prop="canPay">
          <el-switch :active-value="true" :inactive-value="false" v-model="form.canPay" active-color="#13ce66" inactive-color="#ff4949">
          </el-switch>
        </el-form-item>

        <el-form-item label="可退款" size="mini" prop="canRefund">
          <el-switch :active-value="true" :inactive-value="false" v-model="form.canRefund" active-color="#13ce66" inactive-color="#ff4949">
          </el-switch>
        </el-form-item>

        <el-form-item label="可转账" size="mini" prop="canTransfer">
          <el-switch :active-value="true" :inactive-value="false" v-model="form.canTransfer" active-color="#13ce66" inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="自定义参数" size="mini">
          <el-button size="mini" type="primary" @click="handleAddParam">添加</el-button>
        </el-form-item>

        <div v-for="(item, key) in params" :key="key">
          <el-form-item label="参数" size="mini">
            <el-input placeholder="" v-model="item.label" @keyup.enter.native="submit" clearable style="width: 150px"></el-input>
          </el-form-item>
          <el-form-item label="值" size="mini">
            <el-input placeholder="" v-model="item.value" @keyup.enter.native="submit" clearable style="width: 250px"></el-input>
            <el-button size="mini" @click="handleDelParam(key)">移除</el-button>
          </el-form-item>
        </div>
      </el-row>

      <el-form-item label="PS:" size="mini">
        所选银行固定的参数请勿删除，否则影响下单
      </el-form-item>

    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="close" size="small">取 消</el-button>
      <el-button type="primary" @click="submit" size="small" :loading="loading">提 交</el-button>
    </div>

  </el-dialog>
</template>

<script>

import ApiMain from '@/api/bank.channel';
import BankInfoApiMain from '@/api/bank.info';
import RiskCollectionApiMain from '@/api/risk.collection';
import PayPageApiMain from '@/api/bank.payPage';
import ApiRateBoc from '@/api/exchangeRate.rateBoc';
import CardTypeApiMain from '@/api/platform.cardType';
import ChannelApiMain from '@/api/bank.channel';
export default {
  mixins: [
  ],
  props: [
  ],
  data() {
    return {

      dialogVisible: false,
      popDeleteVisible: false,
      loading: false,

      form: {
        channelNo: '',
        channelName: '',
        bankId: '',
        englishBillName: '',
        cardType: '',
        settleCurrency: '',
        country: '',
        channelType: '',
        riskCollectionId: '',
        params: '{}',
        status: '1',
        remark: '',
        payType: null,
        canPay     : true,
        canRefund  : true,
        canTransfer: true,
      },
      payTypeOption: [],
      params: [],

      rules: {
        channelName: [
          { required: true, message: '请输入通道名称', trigger: 'blur' },
        ],
        bankId: [
          { required: true, message: '请选择银行', trigger: 'blur' },
        ],

        cardType: [
          { required: true, message: '请选择卡种', trigger: 'blur' },
        ],

        settleCurrency: [
          { required: true, message: '请选择结算币种', trigger: 'blur' },
        ],

        channelType: [
          { required: true, message: '请选择通道类型', trigger: 'blur' },
        ],
        payType: [
          { required: true, message: '请选择支付类型', trigger: 'blur' },
        ],
        riskCollectionId: [
          { required: true, message: '请选择风控规则集合', trigger: 'blur' },
        ],
      },

      id: null,
      data: null,

      bankOptions: [],
      payPageOptions: [],
      riskCollectionOptions: [],

      currencyOptions: [],
      cardTypeOptions: [],
      channelTypeOptions: [
        { label: '国内结算', value: 1 },
        { label: '国外结算', value: 2 },
      ]
    }
  },
  mounted() {
    this.fetchBankOptions()
    this.fetchPayPageOptions()
    this.fetchRiskCollectionOptions()
    this.fetchCurrencyOptions()
    this.fetchCardTypeOptions()
    this.getPayTypeOption()
  },

  methods: {

    show(id = null) {

      this.reset();

      this.id = id;

      if (this.id) {
        this.fetchData();
      }

      this.dialogVisible = true;
    },

    close() {
      this.dialogVisible = false;
      this.$emit('dialog-close');
    },

    reset() {
      this.form = {
         channelNo: '',
        channelName: '',
        bankId: '',
        englishBillName: '',
        cardType: '',
        settleCurrency: '',
        country: '',
        channelType: '',
        riskCollectionId: '',
        params: '{}',
        status: '1',
        remark: '',
        payType: null,
        
        canPay     : true,
        canRefund  : true,
        canTransfer: true,
      };
      this.params = []
    },

    handleAddParam() {
      this.params.push({ label: '', value: '' })
    },

    handleDelParam(key) {
      this.params.splice(key, 1)
    },

    async fetchCurrencyOptions() {
      // todo 这里是币种
      // this.currencyOptions = await ApiRateBoc.getrateBocOptions();
      this.currencyOptions = await ApiRateBoc.getrateBocOptions({ page: 1, limit: 1 });
      console.log('币种', this.currencyOptions)
    },

    async fetchCardTypeOptions() {
      this.cardTypeOptions = await CardTypeApiMain.option();
    },

    bankChange() {
      BankInfoApiMain.param({ id: this.form.bankId }).then(re => {
        this.form.params = JSON.stringify(re);
        this.handleParseParams();
      })
    },
    getPayTypeOption() {
      ChannelApiMain.payOption().then(res => {
        this.payTypeOption = res
      })
    },
    fetchRiskCollectionOptions() {
      RiskCollectionApiMain.option({ type: 3 }).then(re => {
        this.riskCollectionOptions = re
      })
    },

    fetchBankOptions() {
      BankInfoApiMain.option().then(re => {
        console.log('银行', re)
        this.bankOptions = re
      })
    },

    fetchPayPageOptions() {
      this.payPageOptions = []
    },

    fetchData() {

      ApiMain.info({ id: this.id })
        .then(re => {
          this.data = re;
        })
        .catch(() => {
          this.data = null;
        })
        .finally(() => {
          this.renderData();
        });
    },

    renderData() {
      this.form.channelNo = this.data.channelNo;
      this.form.channelName = this.data.channelName;
      this.form.bankId = this.data.bankId;
      this.form.cardType = this.data.cardType;
      this.form.settleCurrency = this.data.settleCurrency;
      this.form.country = this.data.country;
      this.form.channelType = this.data.channelType;
      this.form.payType = this.data.payType;
      this.form.riskCollectionId = this.data.riskCollectionId;
      this.form.status = this.data.status + '';
      this.form.params = this.data.params;
      this.form.remark = this.data.remark;
      this.form.canPay = !!this.data.canPay;
      this.form.canRefund = !!this.data.canRefund;
      this.form.canTransfer = !!this.data.canTransfer;
      this.handleParseParams()
      console.log(this.form)
    },

    verifyForm() {
      var bool = true;
      this.$refs['main-form'].validate((valid) => bool = valid);
      return bool;
    },

    async submit() {
      if (!this.verifyForm()) return false;

      this.loading = true;

      try {
        if (this.id) {
          await this.submitSet();
        }
        else {
          await this.submitAdd();
        }
      } finally {
        this.loading = false;
      }
    },

    async submitDel() {

      this.popDeleteVisible = false;
      this.loading = true;

      await ApiMain.del({ id: this.id });

      this.loading = false;
      this.close();
      this.$message({ message: '删除成功', type: 'success' });
    },

    async submitSet() {

      this.form.id = this.id;

      let form = Object.assign({}, this.form)
      form.params = this.handleStringParams()


      console.log(JSON.stringify(form, null, 1));

      try {
        await ApiMain.set(form);
        this.$message({ message: '修改成功', type: 'success' });
        this.close();
      } catch (e) { }

    },

    async submitAdd() {

      let form = Object.assign({}, this.form)
      form.params = this.handleStringParams()
      await ApiMain.add(form);
      this.$message({ message: '添加成功', type: 'success' });
      this.close();
    },

    handleStringParams() {
      let params = {}
      for (var i in this.params) {
        params[this.params[i].label] = this.params[i].value
      }
      return JSON.stringify(params)
    },

    handleParseParams() {
      let params = JSON.parse(this.form.params)
      this.params = []
      for (var i in params) {
        this.params.push({ label: i, value: params[i] })
      }
    }
  }
}
</script>

<style>
</style>
